// 个人信息
var V_right = Backbone.View.extend({
	el : "#content",

    flag : false,

	render : function(){
        var self = this;
        if(! self.flag){
            m_personal.fetch({
                success : function(model){
                    if(model.get('type') == "personal"){
                        var template1 = _.template($('#right_top').html())({
                            personal : model.attributes
                        });
                        $('.content_right').html(template1);
                    }
                },
                error: function (obj) {
                    alert('false');
                }
            });

            m_workplacaMission.fetch({
                success : function(model){
                    console.log(model);
                    if(model.get('type') == 'missionCount'){
                        var template2 = _.template($('#right_bottom').html())({
                            personal : model.attributes
                        });
                        $('.right_top').after(template2);
                    }
                },
                error: function (obj) {
                    alert('false');
                }
            });

            self.flag = true;
        }
	},

	events : {
		"click .metion" : "turnIng",
		"click .metion_right" : "turnFin"
	},

	"turnIng" : function(){
		if (if_open()) {}else{$('#aside .task_list').trigger('click');}
		$('#aside .ing_task').trigger('click');
	},

	"turnFin" : function(){
		if (if_open()) {}else{$('#aside .task_list').trigger('click');}
		$('#aside .fin_task').trigger('click');
	}

});

// 侧边栏
var V_task = Backbone.View.extend({
	el : "#main",

    template : function(){
        var self = this;
        var template = _.template($('#aside_template').html())({
            std_name : m_personal.get('std_name')
        });
        $('#aside').html(template);
        $('#aside .task_list').click(function(){

            branch_animate();
            task_onclick();
        });
        $('#aside .orange').click(function () {
            var the = this;
            task_onclick(the);
            branch_onclick();
        });
        $('#aside .branch li').click(function () {
            var the = this;
            branch_onclick(the);
            task_onclick();
        });
    },

	render : function(){
        var self = this;
        if(! m_personal.get('std_name')){
            m_personal.fetchData({
                success : function(){
                    self.template();
                },
                error : function(error){
                    alert(error);
                }
            })
        }
        else{
            self.template();
        }

	},

	events : {
		"click .all_task" : "allTask",
		"click .ing_task" : "ingTask",
		"click .fin_task" : "finTask",
		"click .unfin_task" : "unfinTask",
		"click .pub_task" : "pubTask",
		"click .put_task" : "putTask",
        "click .personal " : "personal",
        'click .wenda' : "answer",
        "click .tongxun" : "chat",
        "click .re_con" : "personalEdit",
        "click .guanli" : "pub_boardcast"
 	},
    "pub_boardcast" : function(){
        route.navigate('/boardcast', {trigger: true});
    },

    "personalEdit" : function(){
        route.navigate('/personalEdit', {trigger: true});
    },

    "chat" : function(){
        alert("暂未开放！");
    },

    "answer" : function(){
        alert('暂未开放！');
    },

    "personal" : function(ev){
        route.navigate('/personal', { trigger : true });
    },

	"allTask" : function(ev){
        // 添加路由
//		$('.task_con').empty();
//		$('#content .list_kind li').html('全部任务');
//		v_all.render();
        time = 1;
        createPage();
        route.navigate('/all', {trigger: true});
	},

	"ingTask" : function(ev){
//		$('.task_con').empty();
//		$('#content .list_kind li').html('待完成任务');
//		v_ing.render();
        time = 1;
        createPage();
        route.navigate('/ing', { trigger: true});
	},

	"unfinTask" : function(ev){
//		$('.task_con').empty();
//		$('#content .list_kind li').html('已过期任务');
//		v_unfin.render();
        time = 1;
        createPage();
        route.navigate('/unfinish', { trigger: true });
	},
    "pubTask" : function(ev){
        ev.preventDefault();

        route.navigate("/publish", { trigger: true});
    },

	"finTask" : function(ev){
//		$('.task_con').empty();
//		$('#content .list_kind li').html('已完成任务');
//		v_fin.render();
        time = 1;
        createPage();
        route.navigate("/finish", { trigger: true})
	},


	"putTask" : function(ev){
//		$('.task_con').empty();
//		$('#content .list_kind li').html('提交列表');
//		v_puttask.render();
        time = 1;
        createPage();
        route.navigate('/pub_task', { trigger: true });
	}
});

// 待完成任务
var V_ing = Backbone.View.extend({
	el : "#content",

    template : function(){
        var the = this;
        var ing = Page(m_mission.get('unfinished'),the);


        if(ing.length == 0){
            $(".page_num").hide();
            return;
        }
        $(".list_kind_ul").html("<li class='list target' id='list_kind'>待完成任务</li>");

        var template = _.template($('#task_ing_template').html())({
            ing : ing
        });

        $("#list_kind").html(m_mission.get("unfinished")['state']);

        $('.task_con').html(template);
        $('.task_con .more_less').click(function () {
            var the = this;
            tasklist(the);
        });
    },

	render : function(){
        var self = this;
        if(! m_mission.get("type")){
            m_mission.fetchData({
                success : function(){
                    self.template();
                },
                error : function(error){
                    alert(error);
                }
            })
        }
        else{
            self.template();
        }

	},

    events : {
        "click .upload_task" : "upload_task",
        "click .upload-button" : "upload_file"
    },


    "upload_task" : function(){
        alert("暂未开放!");
    },

    "upload_file" : function(ev){

        var work_id = $(ev.target).parent().find(".work_id").val();


        $(".fileupload").on('change', function(ev){

            var file = ev.target.files[0];

            var formData = new FormData();


            if(! file) return;

            var name = file.name;

            var headers = {
                Authorization: 'Bearer YOUR_ACCESS_TOKEN'
            };

            var id = m_personal.get('id'),
                type = 'homework',
                std_id = m_personal.get('std_id'),
                std_name = m_personal.get('std_name'),
                std_department = m_personal.get('std_department');

            formData.append("id", id);
            formData.append("type", type);
            formData.append("std_id", std_id);
            formData.append("std_name", std_name);
            formData.append("std_department", std_department);
            formData.append("std_file", file);
            formData.append("work_id", work_id);


            if(/\.(zip|rar?)$/.test(name)){
                $.ajax({
                    url: URL.upload,
                    headers: headers,
                    type: 'POST',
                    // This prevents JQuery from trying to append the form as a querystring
                    processData: false,
                    contentType: false,
                    data: formData
                }).complete(function ( data ) {
                    // Log the JSON response to prove this worked
                    alert("上传成功！");
                    route.navigate("/personal", {trigger: true});
                });
                // /$.ajax({
                //    type : "POST",
                //    url : URL.upload,
                //    enctype : "multipart/form-data",
                //    data : formData,
                //    success : function(data){
                //        alert('上传成功！');
                //    },
                //    error : function(error){
                //        alert("上传失败" + "Error: " + error);
                //    }
                //});
            }


        })

    }
});

// 未完成任务
var V_unfin = Backbone.View.extend({
	el : "#content",

    template : function(){
        var the = this;
        var expire = Page(m_mission.get('expire'),the);


        if(expire.length == 0){
            $(".page_num").hide();
            return;
        }

        $(".list_kind_ul").html("<li class='list target' id='list_kind'>已过期任务</li>");
        var template = _.template($('#task_unfin_template').html())({
            unfinished : expire
        });

        $("#list_kind").html(m_mission.get("expire")['state']);

        $('.task_con').html(template);
        $('.task_con .more_less').click(function () {
            var the = this;
            tasklist(the);
        });
    },

	render : function(){
        var self = this;
        if(! m_mission.get("type")){
            m_mission.fetchData({
                success : function(){
                    self.template();
                },
                error : function(error){
                    alert(error);
                }
            });
        }
        else{
            self.template();
        }
	}

});

//
var V_fin = Backbone.View.extend({
	el : "#content",

    template : function(){
        var the = this;
        var finished = Page(m_mission.get('finished'),the);



        if(finished.length == 0){
            $(".page_num").hide();
            return ;
        }
        $(".list_kind_ul").html("<li class='list target' id='list_kind'>已完成任务</li>");
        var template = _.template($('#task_fin_template').html())({
            finished : finished
        });
        $('.task_con').html(template);

        $("#list_kind").html(m_mission.get("finished")['state']);

        $('.task_con .more_less').click(function () {
            var the = this;
            tasklist(the);
        });
    },

	render : function(){
        var self = this;
        if(! m_mission.get("type")){
            m_mission.fetchData({
                success : function(){
                    self.template();
                },
                error : function(error){
                    alert(error);
                }
            })
        }
        else {
            self.template();
        }


	}
});

var V_all = Backbone.View.extend({
	el : "#content",

    render : function(){
        var self = this;

        m_mission.fetchData({
            success : function(model){
                var the = self;


                var total = Page(m_mission.get('total'), the);


                if(total.length == 0){

                    $(".page_num").hide();
                    return ;
                }
                $(".list_kind_ul").html("<li class='list target' id='list_kind'>全部任务</li>");

                var template = _.template($('#task_all_template').html())({
                    total : total
                });

                $('.task_con').html(template);

                $("#list_kind").html(m_mission.get("total")['state']);

                $('.task_con .more_less').click(function () {
                    var the = this;
                    tasklist(the);
                });

            },
            error : function(error){

            }
        })
	}
});

// 提交列表
var V_putTask = Backbone.View.extend({
    el : "#content",
    render : function(){
        var m_puttask = new M_puttask();

        if($(".page_num").css('display') == 'block'){
            $(".page_num").hide();
        }

        Backbone.sync("read", m_puttask, {
            success : function(model){
                console.log(model);
                var template = _.template($('#putTask_template').html())({
                    putTask : model['missions']
                });
                $('.task_con').html(template);

            },
            error: function (obj) {
                alert('put error!');
            }
        });
    },
    events : {
        "click .modify" : "modify"
    },

    "modify" : function(){
        alert("message");
    }
});

// 个人中心
var V_boardCast = Backbone.View.extend({
    el: ".content_left",

    render:function(options){

        var department = options.department;

        var id = options.id;

        if($(".page_num").css('display') == 'block'){
            $(".page_num").hide();
        }

        if(! id){
             Backbone.sync("read", m_broadcast, {
                success : function(data){
                    var keys = Object.keys(data);

                    for(var i = 0,len = keys.length; i < len; i++){
                        b_collection.set(data[keys[i]]);
                    }
                    if(!department){
                        department = keys[0];
                    }

                    var template = _.template($("#broadcast").html())({
                        department : data[department]
                    });

                    $(".list_kind_ul").html("<li class='list target' id='list_kind'>修改公告</li>");

                    $('.task_con').html(template);
                    var ul = $(".list_kind_ul").html("");

                    var departments = Object.keys(data);

                    for(var i = 0, len = departments.length; i < len;  i ++){
                        if(departments[i] == department){
                            ul.append("<li class='list target' id='list_kind'>" + departments[i] + "</li>");
                        }
                        else{
                            ul.append('<li class="list">' + departments[i] +'</li>');
                        }
                    }
                },
                error : function(obj){
                    alert("error!");
                }
            });
        }
        else if(id){
            var template = _.template($("#boardCast_template").html())({
                title : b_collection.get(id).get('title'),
                department : b_collection.get(id).get('department'),
                content : b_collection.get(id).get("content"),
                id : id
            });

            $('.task_con').html(template);
            $("#list_kind").html(department);
        }
    },

    events : {
        "click .gai" : "change_broadcast",
        "click .list" : "change_department"
    },

    "change_broadcast" : function(ev){
        var id = ev.target.dataset['department'];
        route.navigate("/broadcastEdit/" + id, { trigger : true})
    },

    "change_department" : function(ev){

        var department = ev.target.innerHTML;
        route.navigate('/personal/' + department, {trigger: true});
    }
});

// 发布任务
var V_ul = Backbone.View.extend({
    el : "#publish_form",

    template : function(){
        var template = _.template($("#publish_template").html())();
        $('.task_con').html(template);
        var input = document.getElementsByClassName("annoce_con")[0];
        var ul = input.getElementsByTagName("ul")[0];
        var data = jQuery.parseJSON(ul.dataset['people']);

        for(var i = 0, len = data.length; i <len ; i ++){
            var person_name = data[i].std_name;
            var person_id = data[i].id;
            $(ul).append("<li data-id=" + person_id +">" + person_name +"</li>");
        }

        $(".annoce_con li").on('click',function(){    //人员选择
            var dataId = $(this).attr('data-id');
            var text = $(this).html();
            var id = [];
            id = $("#stu_id").attr('value').split(',');
            if(_.indexOf(id,dataId) == -1){
                var div = $('<div class="personwrap"><span class="close">&#xf0018</span></div>');
                div.append(text);
                div.attr('data-id',dataId);
                $(".people_choose").append(div);
                var beforeId = $('#stu_id').attr('value');
                var newId  = beforeId +','+ dataId;
                $("#stu_id").attr('value',newId);
            }else{
                alert("亲，你已经选择过ta了拉~")
            }
            $(".annoce_con ul").hide();
        });

        $(".people_choose").on('click','.close',function(){     //删除人员
            var dataId = $(this).parent().attr('data-id');
            var anotherId = [];
            var filtered = [];
            anotherId = $("#stu_id").attr("value").split(",");
            filtered = _.without(anotherId,dataId);
//              console.log(filtered);
            var newId = filtered.join(",");
//              console.log(typeof(newId));
            $("#stu_id").attr('value', newId);
            $(this).parent().remove();
        })

    },

    ulShow : function(input){
        var self = this;
        var input = document.getElementsByClassName("annoce_con")[0];

        var div = input.getElementsByClassName("people_choose")[0];
        var ul = input.getElementsByTagName("ul")[0];
        $(div).on('click', function(){
            $(ul).show();
        });

        $(".page_num").hide();

    },

    render : function(){
        var self = this;
        self.template();
        self.ulShow();
        if($(".page_num").css('display') == 'block'){
            $(".page_num").hide();
        }

        $("#publish_form").on('submit', function(ev){
            var data = $("#publish_form").serializeObject();

            data.id = m_personal.id;
            data.type = "publish";

            data.stu_id = data.id.split(",");

            $.post(URL.publish, data, function(model){
                if(model.state == 200){
                    alert("发布成功！");
                    route.navigate('/personal', {trigger : true});
                }
            });

            return false;
        });


        $(".normal").on('click', function(){
            $(".people_choose").hide();
        })

        $("#others").on('click', function(){
            $(".people_choose").show();
        });
    }
});

// 个人信息
var V_personal = Backbone.View.extend({
    el : ".task_con",

    template : function(){

        var template = _.template($("#personal_template").html())({
            personal : m_personal.attributes
        });
        $(".list_kind_ul").html("<li class='list target' id='list_kind'>个人信息</li>");
        $('.task_con').html(template);

    },


    render : function(options){
        var self = this;
        if($(".page_num").css('display') == 'block'){
            $(".page_num").hide();
        }


        if(! m_personal.id){
            m_personal.fetch({
                success : function(model){
                    self.template();
                },
                error: function (obj) {
                    alert('false');
                }
            });
        }
        else{
            self.template();
        }
    },

    events : {
        "submit #personal_form" : "submitEvent"
    },

    "submitEvent" : function(ev){
        var data = $(ev.target).serializeObject();

        m_personal.set(data);

        m_personal.save(data, {
            url : URL.personalEdit,
            success : function(model){
                if(model.get('state') == '200'){
                    alert("修改成功！");
                    route.navigate("/", { trigger: true });
                }
                else if(model.get('error')){
                    alert(model.get('error'));
                }
            }
        })


        return false;
    }
});


// 发布公告
var V_boardCastPub = Backbone.View.extend({
    el : ".task_con",

    "currentTime" : function(){
            var now = new Date();

            var year = now.getFullYear();       //年
            var month = now.getMonth() + 1;     //月
            var day = now.getDate();            //日

            var hh = now.getHours();            //时
            var mm = now.getMinutes();          //分

            var clock = year + "-";

            if(month < 10)
                clock += "0";

            clock += month + "-";

            if(day < 10)
                clock += "0";

            clock += day + " ";

            if(hh < 10)
                clock += "0";

            clock += hh + ":";
            if (mm < 10) clock += '0';
            clock += mm;
            return(clock);
    },

    "template" : function(id){


        var template = _.template($("#boardCast_template").html())({
            department : "",
            content : "",
            title : "",
            id : id
        });

        $(".list_kind_ul").html("<li class='list target' id='list_kind'>发布公告</li>");

        $(".task_con").html(template);

        return this;
    },

    render : function(options){
        var self = this;
        if($(".page_num").css('display') == 'block'){
            $(".page_num").hide();
        }



        var id = options['id'] || "";

        self.template();

    },

    events : {
        'submit .pub_boardcast' : "form_submit"
    },

    "form_submit" : function(ev){
        var data = $(ev.target).serializeObject();
        ev.preventDefault();
        var self = this;



        data.type = "broadcast";

        data.time = self.currentTime();

        m_broadcast.set(data);


        if(! data.id){
            m_broadcast.save(data, {
                url : URL.broadcastPub,
                success : function(){
                    alert("发布成功！");
                    route.navigate('/personal', {trigger : true });
                },
                error : function(error){
                    console.log(error);
                }
            });
        }
        else{
            m_broadcast.save(data, {
                url : URL.broadcastEdit,
                success : function(){
                    alert("修改成功!！");
                    route.navigate('/personal', {trigger : true });
                },
                error : function(error){
                    console.log(error);
                }
            });
        }



        return false;
    }
});


var v_boardCastPub = new V_boardCastPub();
var v_personal = new V_personal();
var v_ul = new V_ul();
var v_right = new V_right();
var v_task = new V_task();
var v_all = new V_all();
var v_ing = new V_ing();
var v_unfin = new V_unfin();
var v_fin = new V_fin();
var v_put = new V_putTask();
var v_boardCast = new V_boardCast();